<template>
  <div class="material-upload-container">
    <el-card class="upload-card">
      <template #header>
        <h2>上传资料</h2>
      </template>

      <el-form 
        ref="uploadForm" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="top"
      >
        <!-- 文件上传 -->
        <el-form-item label="选择文件" prop="file">
          <el-upload
            class="uploader"
            drag
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpg,.jpeg,.png,.zip,.rar"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击选择</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持格式：Word/Excel/PPT/PDF/图片/ZIP/RAR，大小不超过50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 资料标题 -->
        <el-form-item label="资料标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入资料标题" />
        </el-form-item>

        <!-- 资料描述 -->
        <el-form-item label="资料描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入资料描述"
          />
        </el-form-item>

        <!-- 分类选择 -->
        <el-form-item label="分类" prop="categoryId">
          <el-cascader
            v-model="form.categoryId"
            :options="categories"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择分类"
            clearable
          />
        </el-form-item>

        <!-- 标签输入 -->
        <el-form-item label="标签">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="输入标签，按回车确认"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.name"
            />
          </el-select>
        </el-form-item>

        <!-- 价格设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格(虚拟币)" prop="price">
              <el-input-number
                v-model="form.price"
                :min="0"
                :max="1000"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="无水印版本额外价格" prop="noWatermarkPrice">
              <el-input-number
                v-model="form.noWatermarkPrice"
                :min="0"
                :max="1000"
                placeholder="请输入额外价格"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 水印设置 -->
        <el-form-item label="水印设置">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input
                v-model="form.watermarkText"
                placeholder="水印文字"
              />
            </el-col>
            <el-col :span="6">
              <el-select v-model="form.watermarkPosition" placeholder="位置">
                <el-option label="左上" value="top-left" />
                <el-option label="右上" value="top-right" />
                <el-option label="左下" value="bottom-left" />
                <el-option label="右下" value="bottom-right" />
                <el-option label="居中" value="center" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-slider
                v-model="form.watermarkOpacity"
                :min="0.1"
                :max="1"
                :step="0.1"
                show-input
              />
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            :loading="uploading"
            @click="submitUpload"
          >
            上传资料
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 上传进度对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="上传进度"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-progress
        :percentage="uploadProgress"
        :status="uploadStatus"
      />
      <div v-if="uploadMessage" class="progress-message">
        {{ uploadMessage }}
      </div>
      <template #footer>
        <el-button
          v-if="uploadStatus === 'success'"
          type="primary"
          @click="handleUploadSuccess"
        >
          完成
        </el-button>
        <el-button
          v-if="uploadStatus === 'exception'"
          type="danger"
          @click="resetUpload"
        >
          重试
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getCategories, getTags } from '@/api/material'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const form = reactive({
  file: null,
  title: '',
  description: '',
  categoryId: null,
  tags: [],
  price: 0,
  noWatermarkPrice: 0,
  watermarkText: '标王资料网',
  watermarkPosition: 'bottom-right',
  watermarkOpacity: 0.5
})

// 表单验证规则
const rules = reactive({
  file: [
    { required: true, message: '请选择文件', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入资料标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ]
})

// 文件列表
const fileList = ref([])

// 分类和标签数据
const categories = ref([])
const availableTags = ref([])

// 上传状态
const uploading = ref(false)
const progressDialogVisible = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const uploadMessage = ref('')

// 加载分类和标签
onMounted(async () => {
  try {
    const [cats, tags] = await Promise.all([
      getCategories(),
      getTags()
    ])
    categories.value = cats.data
    availableTags.value = tags.data
  } catch (error) {
    console.error('加载分类和标签失败:', error)
    ElMessage.error('加载分类和标签失败')
  }
})

// 文件选择变化
const handleFileChange = (file) => {
  form.file = file.raw
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件')
}

// 提交上传
const submitUpload = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return router.push('/login')
  }

  if (!form.file) {
    ElMessage.warning('请选择文件')
    return
  }

  uploading.value = true
  progressDialogVisible.value = true
  uploadStatus.value = ''
  uploadMessage.value = '正在上传...'

  try {
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', form.file)
    formData.append('title', form.title)
    formData.append('description', form.description)
    formData.append('categoryId', form.categoryId[form.categoryId.length - 1])
    formData.append('price', form.price)
    formData.append('noWatermarkPrice', form.noWatermarkPrice)
    formData.append('watermarkText', form.watermarkText)
    formData.append('watermarkPosition', form.watermarkPosition)
    formData.append('watermarkOpacity', form.watermarkOpacity)
    
    // 添加标签
    form.tags.forEach(tag => {
      formData.append('tags[]', tag)
    })

    // 模拟上传进度
    const interval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += 10
      }
    }, 300)

    // TODO: 调用API上传
    // const response = await uploadMaterial(formData, {
    //   onUploadProgress: (progressEvent) => {
    //     uploadProgress.value = Math.round(
    //       (progressEvent.loaded * 100) / progressEvent.total
    //     )
    //   }
    // })

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    clearInterval(interval)
    uploadProgress.value = 100
    uploadStatus.value = 'success'
    uploadMessage.value = '上传成功！'

    // 实际使用时取消注释下面这行
    // ElMessage.success('资料上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    uploadStatus.value = 'exception'
    uploadMessage.value = error.response?.data?.message || '上传失败，请重试'
    ElMessage.error('上传失败')
  } finally {
    uploading.value = false
  }
}

// 上传成功处理
const handleUploadSuccess = () => {
  progressDialogVisible.value = false
  router.push('/materials')
}

// 重置上传状态
const resetUpload = () => {
  progressDialogVisible.value = false
  uploadProgress.value = 0
  uploadStatus.value = ''
  uploadMessage.value = ''
}
</script>

<style scoped>
.material-upload-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.upload-card {
  margin-top: 20px;
}

.uploader {
  width: 100%;
}

.progress-message {
  margin-top: 10px;
  text-align: center;
  color: var(--el-text-color-secondary);
}
</style>